<?php

namespace addons\member\user\controller;

/**
 * Description of Record
 * 交易记录
 * @author shilinqing
 */
class Record extends \web\user\controller\AddonUserBase{
    
    public function index(){
        $m = new \addons\config\model\BalanceConf();
        $list = $m->getDataList(-1,-1,'','id,name','id asc');
        $this->assign('confs',$list);
        $typeM = new \addons\member\model\TradingRecordType();
        $type_list = $typeM->getDataList(-1,-1,'','id,type_name','id asc');
        $this->assign('type_list',$type_list);
        $type_arr = (new \addons\member\model\TradingRecordType())->column('id,type_name');
        $this->assign('type_json',json_encode($type_arr));
        $store_id = $this->store_id??0;
        $this->assign('store_id', $store_id);
        return $this->fetch();
    }
    
    public function loadList(){
        $keyword = $this->_get('keyword');
        $asset_type = $this->_get('asset_type');
        $change_type = $this->_get('change_type');
        $type = $this->_get('type');
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        $filter = '1=1';


        if($this->store_id > 0){
            $storeM = new \addons\shop\model\Store();
            $user_id = $storeM->getDetail($this->store_id, 'user_id')['user_id'];
            if($user_id > 0){
                $filter .= ' a.type=42 and a.user_id='.$user_id;
            }
        }

        if($type != ''){
            $filter .= ' and a.type='.$type;
        }
        if($asset_type != ''){
            $filter .= ' and a.asset_type='.$asset_type;
        }
        if($change_type != ''){
            $filter .= ' and a.change_type='.$change_type;
        }
        if ($keyword != null) {
            // $filter .= ' and b.username like \'%' . $keyword . '%\'';
            $filter .= ' and (b.username like \'%' . $keyword . '%\' or b.phone  like \'%' . $keyword . '%\')';
        }
        if ($startDate != null && $endDate != null)
            $filter .= ' and (a.update_time >= \'' . $startDate . ' 00:00:00\' and a.update_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (a.update_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (a.update_time <= \'' . $endDate . ' 23:59:59\')';
        $m = new \addons\member\model\TradingRecord();
        $total = $m->getTradingRecordTotal($filter);

        $fields = 'a.*,b.username,b.phone bphone,c.username as to_username,c.phone as to_phone,trt.type_name,sb.name as balance_name';
        $rows = $m->getTradingRecordList($this->getPageIndex(), $this->getPageSize(), $filter, $fields);
        if($change_type != '')
            $count_total = $m->getCountTradingRecordTotal($filter);
        else{
            $filter1 = $filter .' and a.change_type=1';
            $count_plus_total = $m->getCountTradingRecordTotal($filter1);
            $filter2 = $filter .' and a.change_type=0';
            $count_minus_total = $m->getCountTradingRecordTotal($filter2);
            $count_total = $count_plus_total - $count_minus_total;
        }
        return $this->toTotalDataGrid($total, $rows,$count_total);
    }

    //导出
    public function export(){
        ob_end_clean();
        $keyword = $this->_get('keyword');
        $asset_type = $this->_get('asset_type');
        $change_type = $this->_get('change_type');
        $type = $this->_get('type');
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        $filter = '1=1';
        if($type != ''){
            $filter .= ' and type='.$type;
        }
        if($asset_type != ''){
            $filter .= ' and asset_type='.$asset_type;
        }
        if($change_type != ''){
            $filter .= ' and change_type='.$change_type;
        }
        if ($keyword != null) {
            $filter .= ' and username like \'%' . $keyword . '%\'';
        }
        if ($startDate != null && $endDate != null)
            $filter .= ' and (update_time >= \'' . $startDate . ' 00:00:00\' and update_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (update_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (update_time <= \'' . $endDate . ' 23:59:59\')';
        $fileName = '交易记录_'.NOW_DATETIME.'.csv';
        header('Content-type: text/html;charset=utf-8');
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');
        $header = [
            ['title' => '编号', 'field' => 'id'],
            ['title' => '用户名', 'field'=> 'username'],
            ['title' => '资产类型', 'field'=> 'asset_type'],
            ['title' => '变更类型', 'field'=> 'change_type'],
            ['title' => '记录类型', 'field'=> 'type'],
            ['title' => '变更前金额', 'field' => 'before_amount'],
            ['title' => '变更金额', 'field' => 'amount'],
            ['title' => '变更后金额', 'field'=> 'after_amount'],
            ['title' => '时间', 'field'=> 'update_time'],
            ['title' => '备注', 'field'=> 'remark'],
        ];

//         将数据通过fputcsv写到文件句柄
//         CSV的Excel支持GBK编码，一定要转换，否则乱码
        $head = [];
        foreach($header as $val){
            $head[] = iconv('utf-8', 'gbk', $val['title']);
        }
        fputcsv($fp, $head);
        $asset_arr = (new \addons\config\model\BalanceConf())->column('id,name');

        $change_arr = [
            '0' => '减少',
            '1' => '增加'
        ];
        $type_arr = (new \addons\member\model\TradingRecordType())->column('id,type_name');
        $m = new \addons\member\model\TradingRecord();
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter);
        foreach($rows as $k => $row){
            $rows[$k]['asset_type'] = $asset_arr[$row['asset_type']];
            $rows[$k]['change_type'] = $change_arr[$row['change_type']];
            $rows[$k]['type'] = $type_arr[$row['type']];
        }
        $i = 0;
        // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;
        $data = [];
        foreach ($rows as &$row) {
            if ($limit == $i) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $i = 0;
            }
            $arr = [];
            foreach ($header as $key => $val) {
                $value = isset($row[$val['field']]) ? $row[$val['field']] : "";
                $arr[$val['field']] = iconv('utf-8', 'gbk//IGNORE', $value."\t");
            }
            fputcsv($fp, $arr);
        }
    }
}
